package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.OrderDetail;
import com.itheima.bean.Orders;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import com.itheima.bean.AddressBook;
import com.itheima.bean.User;
import com.itheima.service.AddressBookService;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;


/**
 * @author Tang
 * @date 2023/2/25
 */
@Slf4j
@RequestMapping("/order")
@RestController
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;


    /**
     * 提交订单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {

        //1.调用service的提交订单方法
        ordersService.submit(orders);
        //2.返回结果
        return R.success("提交订单成功！");
    }


    /**
     * 订单分页查询
     */
    @GetMapping("/page")
    public R<Page> page(@RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer pageSize,
                        String number,
                        @DateTimeFormat String beginTime,
                        @DateTimeFormat String endTime) {

        Page<Orders> ordersPage = new Page<>(page, pageSize);

        //Page<OrdersDto> ordersDtoPage = new Page<>();
        //根据订单号模糊匹配
        LambdaQueryWrapper<Orders> olqw = new LambdaQueryWrapper<>();
        olqw.like(number != null, Orders::getNumber, number);
        //根据开始结束时间查询
        olqw.between(beginTime != null || endTime != null,
                Orders::getOrderTime, beginTime, endTime);

        //下单时间倒序排序
        olqw.orderByDesc(Orders::getOrderTime);
        ordersService.page(ordersPage, olqw);

        //保存数据
        //ordersPage.getRecords();
        return R.success(ordersPage);
    }

    /**
     *
     * @param: page
     * @param: pageSize
     * @return : {@link R< Page< OrdersDto>>}
     * @author : Zhonghan
     * @description: 〈订单分页查询〉
     * @date : 2023/4/21 17:18
     */

    @GetMapping("/userPage")
    public R<Page<OrdersDto>> pageUser(@RequestParam Integer page ,
                                   @RequestParam Integer pageSize){
        log.info("订单查询分页展示，page = {}，pageSize = {}",page,pageSize);
        Long UserId = BaseContext.getCurrentId();

        //1.设置分页对象 Page对象
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        //2.设置查询条件
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserId != null,Orders::getUserId,UserId);
        wrapper.orderByDesc(Orders::getOrderTime);
        //3.调用service的分页查询方法
        ordersService.page(ordersPage,wrapper);

        Page<OrdersDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage,dtoPage,"records");

        List<OrdersDto> ordersDtos = new ArrayList<>();

        List<Orders> records = ordersPage.getRecords();
        for (Orders order : records) {
            OrdersDto dto = new OrdersDto();
            //拷贝数据
            BeanUtils.copyProperties(order,dto);
            //填充字段
            //查询订单明细，并封装到orderDetails属性中
            LambdaQueryWrapper<OrderDetail> wrapperDetail = new LambdaQueryWrapper<>();
            wrapperDetail.eq(order.getId() != null,OrderDetail::getOrderId,order.getId());

            List<OrderDetail> details = orderDetailService.list(wrapperDetail);

            dto.setOrderDetails(details);

            //查询地址，并封装数据
            LambdaQueryWrapper<AddressBook> wrapperAddress = new LambdaQueryWrapper<>();
            wrapperAddress.eq(UserId != null,AddressBook::getUserId,UserId);
            wrapperAddress.eq(order.getAddressBookId() != null,AddressBook::getId,order.getAddressBookId());

            AddressBook addressBook = addressBookService.getOne(wrapperAddress);
            User user = userService.getById(addressBook.getUserId());

            dto.setUserName(user.getName());
            dto.setPhone(addressBook.getPhone());
            dto.setAddress(addressBook.getDetail());
            dto.setConsignee(addressBook.getConsignee());

            //计算订单总计金额
            dto.setAmount(order.getAmount());

            ordersDtos.add(dto);

        }
        dtoPage.setRecords(ordersDtos);

        return R.success(dtoPage);

    }
    /**
     * 修改后台管理的订单表状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<Orders> updata(@RequestBody Orders orders) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(orders.getId() != null, Orders::getId, orders.getId());
        ordersService.updateById(orders);
        return R.success(orders);
    }
    
    /**
     * 再来一单
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        ordersService.again(orders);
        return R.success("操作成功");
    }
}

